﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using DAL.Unit;
using System.Data;
using DAL;

namespace BLL.Unit
{
    /// <summary>
    /// 单位管理
    /// </summary>
    public class UnitBLL
    {
        private readonly UnitDAL _unitDAL = new UnitDAL();
        private readonly SqlDbHelper _SqlDbHelper = new SqlDbHelper();
        #region 新增及保存
        /// <summary>
        /// 新增及保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> SaveUnit(UnitModel entity)
        {
            try
            {
                return await _unitDAL.SaveUnit(entity);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

        #region 删除单位对象
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> RemoveUnit(string id)
        {
            try
            {
                return await _unitDAL.RemoveUnit(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion


        #region 获取单位对象
        /// <summary>
        /// 获取单位对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<UnitModel> GetEntity(string id)
        {
            try
            {
                return await _unitDAL.GetEntity(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion


        #region 获取随机验证码的对象
        /// <summary>
        /// 获取随机验证码的对象
        /// </summary>
        /// <param name="seqCode"></param>
        /// <returns></returns>
        public UnitModel GetEntityBySeqCode(string seqCode) 
        {
            try
            {
                return  _unitDAL.GetEntityBySeqCode(seqCode);
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 获取当前节点下的子集合
        /// <summary>
        /// 获取当前节点下的子集合
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<List<UnitModel>> GetListByParentId(string parentId)
        {
            try
            {
                return await _unitDAL.GetListByParentId(parentId);
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 获取所有单位信息
        /// <summary>
        /// 获取所有单位信息
        /// </summary>
        public async Task<List<UnitModel>> GetList()
        {
            try
            {
                return await _unitDAL.GetList();
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 获取单位编码
        /// <summary>
        /// 获取单位编码
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public async Task<string> GetUnitCode(string ParentId)
        {
            string code = string.Empty;
            //当父节点不存在
            if (string.IsNullOrEmpty(ParentId))
            {
                ParentId = "0";
            }
            List<UnitModel> childlist = await GetListByParentId(ParentId);
            UnitModel parentModel = await GetEntity(ParentId);
            if (null != parentModel) 
            {
                childlist = childlist.Where(p => p.UnitCode.StartsWith(parentModel.UnitCode)).ToList();
            }
            if (childlist.Count() > 0)
            {
                UnitModel lastModel = childlist.LastOrDefault();
                string lastcode = lastModel.UnitCode.Substring(lastModel.UnitCode.Length - 6, 6);
                string startcode = string.Empty;
                if (null != parentModel) 
                {
                    startcode = parentModel.UnitCode;
                }
                int newcode = int.Parse(lastcode) + 1;
                string tempcode = string.Empty;
                if (newcode.ToString().Length < 6)
                {
                    for (int i = 0; i < 6 - newcode.ToString().Length; i++)
                    {
                        tempcode += "0";
                    }
                }
                code = startcode + tempcode + newcode.ToString();
            }
            else
            {
                //当parentid为0时，且无对应的子节点，则默认000001
                if (ParentId == "0")
                {
                    code = "000001";
                }
                else
                {
                    code = parentModel.UnitCode + "000001";
                }
            }
            return code;
        }
        #endregion


        #region 递归更新子节点单位编码
        /// <summary>
        /// 递归更新子节点单位编码
        /// </summary>
        /// <param name="unitId"></param>
        /// <returns></returns>
        public async Task UpdateChildUnitCode(string unitId)
        {
            List<UnitModel> list = await GetListByParentId(unitId);
            if (list.Count() > 0)
            {
                foreach (UnitModel model in list)
                {
                    model.UnitCode = await GetUnitCode(model.ParentId);
                    await SaveUnit(model);
                    await UpdateChildUnitCode(model.UnitId);
                }
            }
        } 
        #endregion

        #region 获取随机码
        /// <summary>
        /// 获取随机码
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetRandomCode()
        {
            Random rd = new Random();
            string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string result = "";
            for (int i = 0; i < 6; i++)
            {
                result += str[rd.Next(str.Length)];
            }
            List<UnitModel> list = await _unitDAL.GetListBySeqCode(result);
            while (list.Count() > 0) 
            {
                result = await GetRandomCode();
            }
            return result;
        }
        #endregion


        #region 调用分页存储过程
        /// <summary>
        /// 调用分页存储过程
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="tableName"></param>
        /// <param name="pkId"></param>
        /// <param name="fieldNames"></param>
        /// <param name="strWhere"></param>
        /// <param name="sidx"></param>
        /// <param name="sord"></param>
        /// <param name="total"></param>
        /// <param name="records"></param>
        /// <returns></returns>
        public DataTable GetDataTableByCondition(int pageSize, int pageIndex, string tableName, string pkId, string fieldNames,
            string strWhere, string sidx, string sort, out int total, out int records)
        {
            QueryCondition condition = new QueryCondition();
            DataTable dt = new DataTable();
            try
            {
                condition.pageIndex = pageIndex;
                condition.pageSize = pageSize;
                condition.tableName = tableName;
                condition.fieldNames = fieldNames;
                condition.strWhere = strWhere;
                condition.pkId = pkId;
                condition.sidx = sidx;
                condition.sort = sort;
                dt = _SqlDbHelper.GetPager(condition);
                total = condition.total.Value;
                records = condition.records.Value;
            }
            catch (Exception ex)
            {
                throw;
            }
            return dt;
        }
        #endregion


        #region 获取相同单位下的单位信息
        /// <summary>
        /// 获取相同单位下的单位信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<UnitModel>> GetListByUnitName(string unitName)
        {
            try
            {
                return await _unitDAL.GetListByUnitName(unitName);
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
    }
}
